package band.wukong.practice.javase.core.thread.sync;

/**
 * Desc: 同步代码块中有sleep或yield。
 * Author: sunjs
 * Date: 2009-11-6 11:08:44
 */
public class TestSynWithSleep implements Runnable {
    private static int a = 1;
    protected static final int LOOP_TIMES = 10;

    public void run() {
        for (int i = 0; i < LOOP_TIMES; i++) {
            synchronized (this) {
                a += i;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                a -= i;
                System.out.println(Thread.currentThread().getName() + ": " + a);
            }
        }
    }

    public void go() {
        for (int i = 0; i < LOOP_TIMES; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        TestSynWithSleep m = new TestSynWithSleep();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        t1.start();
        t2.start();
        m.go();
    }
}